package com.xuecheng.framework.exception;


import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;


//异常捕获类
@ControllerAdvice
public class ExceptionCatch {

    //定义map,配置异常类所对应的错误代码
    private static ImmutableMap<Class<? extends Throwable>,ResultCode> EXCEPTIONS;
    //定义map的build对象，去构建ImmutableMap
    public static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder=ImmutableMap.builder();

    //定义可预知异常捕获方法
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException customException){
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult(resultCode);
    }
    //定义不可预知异常捕获方法
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception){

        if(EXCEPTIONS==null){
            EXCEPTIONS = builder.build();
        }
        final ResultCode resultCode =EXCEPTIONS.get(exception.getClass());
        if(resultCode!=null){

            return new ResponseResult(resultCode);
        }else {
            return  new ResponseResult(CommonCode.SERVER_ERROR);
        }
    }

    static{
        builder.put(HttpMessageNotReadableException.class,CommonCode.INVALIDPARAM);
    }
}
